package com.sptpc.book.utils;

import cn.hutool.core.util.NumberUtil;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Locale;
@Component
public class MoneyFormatter implements Formatter<Money> {
    @Override
    public Money parse(String s, Locale locale) throws ParseException {
        if (NumberUtil.isNumber(s)){
            return Money.of(CurrencyUnit.of("CNY"), NumberUtil.toBigDecimal(s));
        }
        throw new ParseException(s,0);
    }

    @Override
    public String print(Money money, Locale locale) {
        if (money==null){
            return null;
        }
        return money.getCurrencyUnit().getCode()+ " " +money.getAmount();
    }
}
